using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DynamicControls
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (cNumber.Text != string.Empty)
                GenerateDynamicControls(int.Parse(cNumber.Text));
        }

        private void GenerateDynamicControls(int amount)
        {
            //Clear existing
            pContainer.Controls.Clear();

            for (int i = 0; i < amount; i++)
            {
                //Create the Textbox
                TextBox dynamicTextbox = new TextBox();
                dynamicTextbox.Name = "dynamicTextbox" + i.ToString();
                dynamicTextbox.Width = 290;
                dynamicTextbox.Height = 20;
                dynamicTextbox.Left = 9;
                dynamicTextbox.Top = 10 + (dynamicTextbox.Height * i) + (10 * i); //initial + height + padding
                dynamicTextbox.Text = "This is textbox number " + (i + 1).ToString();

                //Create the Button
                Button dynamicButton = new Button();
                dynamicButton.Name = "dynamicButton" + i.ToString();
                dynamicButton.Width = 75;
                dynamicButton.Height = 23;
                dynamicButton.Left = dynamicTextbox.Left + dynamicTextbox.Width + 5;
                dynamicButton.Top = dynamicTextbox.Top; //Center the button vertically to textbox
                dynamicButton.Text = "Show";
                dynamicButton.Click += new EventHandler(Button_Click); //hook the Click event

                //Add them to the container
                pContainer.Controls.Add(dynamicTextbox);
                pContainer.Controls.Add(dynamicButton);
            }
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Button clickedButton = (Button)sender; //get the button that was clicked

            
            string index = clickedButton.Name.Substring("dynamicButton".Length);

            string targetTextBox = "dynamicTextbox" + index;

            
            int textBoxIndex = pContainer.Controls.IndexOfKey(targetTextBox);

            if (textBoxIndex != -1)
            {
                TextBox foundTextBox = (TextBox)pContainer.Controls[textBoxIndex];
                MessageBox.Show(foundTextBox.Text);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://itgate.com.vn");
        }
    }
}